﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;


namespace UI
{
    public enum CopyType
    {
        MainLine, //主线
        Group,    //组队
    }
    public class UICopy :Page
    {
        public override void OnCoverPageRemove()
        {
            RefreshDropDetail();
            RefreshStar();
            //CheckLevelUp();
        }

        public CopyType copyType= CopyType.MainLine;
        public GameObject mainLineCopy;
        public GameObject groupCopy;

        //左下角的悬赏boss和料理加成
        public UICopyBossCook bossAndCook; 

        #region static font
        //副本主面板
        public UILabel awardBtnTxt;
        public UILabel rankBtnTxt;
        public UILabel campBtnTxt;
        public UILabel gainTxt;
        public UILabel dropAwardTxt;
        public UILabel mainCopyTxt;
        public UILabel groupCopyTxt;
        public UILabel copyTitleTxt;
        public UILabel powerTxt;
        public UILabel starTxt;
        #endregion

        #region half static font
        public UILabel sweepBtnCountTxt;//{0}
        public UILabel challageBtnTxt;//{0}
        public UILabel curLevelTxt;//{0}
        public UILabel curCostPowerTxt;//{0}
        #endregion

        #region dynamic font
        public UILabel curLevelName;
        public UILabel curPowerTxt;
        public UILabel curStarTxt;
        #endregion

        #region sroll view
        public UIScrollView chapterScrollView;
        public UIScrollView levelScrollVIew;
        #endregion

        #region template
        public GameObject chapterItem;
        public GameObject levelItem;
        public GameObject dropItem; //main panel
        #endregion

        public UIGrid chapterItemGrid;
        public UIGrid levelItemGrid;
        public UIGrid dropItemGrid;

        public UILabel awordMoney;
        public UILabel awordExp;
        public UILabel currLevel;
        public UILabel currLevelName;
        public UILabel currLevelCost;
        public UILabel currChallengeCount;

        public GameObject currAwardTips;

        public UITexture currLevelTex;
        private string copyTextureName;

        #region moveinfo
        Vector3 chapterScrollViewStart;
        Vector3 levelScrollViewStart;

        Vector2 chapterScrollViewClipOffset;
        Vector2 levelScrollViewClipOffset;
        #endregion

        #region ui data
        public string currentSelectionChapterId="-1";
        public string currentSelectionLevelId="-1";
        #endregion

        List<GameObject> chapters = new List<GameObject>();
        List<GameObject> levels = new List<GameObject>();
        List<GameObject> drops = new List<GameObject>();

        public GameObject sweepBtn;

        #region Component Function

        public TweenAlpha bodyTweenAlpha;
        public TweenPosition bodyTweenPosition;
        public TweenScale leftHeadTweenScale;
        public TweenAlpha leftHeadTweenAlpha;
        public TweenPosition titleTweenPosition;

        public TweenAlpha headTab1TweenAlpha;
        public TweenAlpha headTab2TweenAlpha;
        public TweenAlpha headLineTweenAlpha;

        public TweenAlpha heroTopTweenAlpha;
        
        public GameObject fightBtn;
        
        public int currentSweepCount=0;

        public static int currentDay = -1;

        void Awake()
        {
            awardBtnTxt.text = TableTextBlo.GetText( "award" );
            rankBtnTxt.text = TableTextBlo.GetText( "rank" );
            campBtnTxt.text = TableTextBlo.GetText( "embattle" );
            gainTxt.text = TableTextBlo.GetText( "gain" );
            dropAwardTxt.text = TableTextBlo.GetText( "copy_drop_award" );
            challageBtnTxt.text = TableTextBlo.GetText( "copy_battle" );
            sweepBtnCountTxt.text = string.Format( TableTextBlo.GetText( "copy_sweep" ), 10 );

            mainCopyTxt.text = TableTextBlo.GetText( "copy_main_line" );
            groupCopyTxt.text = TableTextBlo.GetText( "copy_group" );
            copyTitleTxt.text = TableTextBlo.GetText( "copy_title_name" );
            powerTxt.text = TableTextBlo.GetText( "power" );
            starTxt.text = TableTextBlo.GetText( "chapter_star" );

          
            chapterScrollViewStart = chapterScrollView.transform.localPosition;
            levelScrollViewStart = levelScrollVIew.transform.localPosition;
            chapterScrollViewClipOffset = chapterScrollView.GetComponent<UIPanel>().clipOffset;
            levelScrollViewClipOffset = levelScrollVIew.GetComponent<UIPanel>().clipOffset;
        }
        void OnEnable()
        {
            chapterScrollView.transform.localPosition = chapterScrollViewStart;
            levelScrollVIew.transform.localPosition = levelScrollViewStart;
            chapterScrollView.GetComponent<UIPanel>().clipOffset = chapterScrollViewClipOffset;
            levelScrollVIew.GetComponent<UIPanel>().clipOffset=levelScrollViewClipOffset;
        }
        void OnDisable()
        {
            chapterScrollView.ResetPosition();
            levelScrollVIew.ResetPosition();
            StopAllCoroutines();
        }
        #endregion
        protected override void DoOpen()
        {
            var evt = GetComponent<UICopyEvent>();
            if(StaticData.copyData.has_init 
                && currentDay==DateTime.Now.Day)
            {
                evt.GetCurrentCopy();
            }
            else
            {
                evt.GetPassedCopy();
                currentDay = DateTime.Now.Day;
                Debug.Log("copy init current day:" + currentDay);
            }
            
            DoTween();
        }

        void DoTween()
        {
            bodyTweenAlpha.ResetToBeginning();
            bodyTweenPosition.ResetToBeginning();
            leftHeadTweenScale.ResetToBeginning();
            titleTweenPosition.ResetToBeginning();
            headTab1TweenAlpha.ResetToBeginning();
            headTab2TweenAlpha.ResetToBeginning();
            headLineTweenAlpha.ResetToBeginning();
            leftHeadTweenAlpha.ResetToBeginning();
            heroTopTweenAlpha.ResetToBeginning();

            bodyTweenAlpha.PlayForward();
            bodyTweenPosition.PlayForward();
            leftHeadTweenScale.PlayForward();
            titleTweenPosition.PlayForward();
            headTab1TweenAlpha.PlayForward();
            headTab2TweenAlpha.PlayForward();
            headLineTweenAlpha.PlayForward();
            heroTopTweenAlpha.PlayForward();
            leftHeadTweenAlpha.PlayForward();
        }

        public void RefreshOrNext()
        {
            var tempChapterId = StaticData.currFightChapterId;
            var tempLevelId = StaticData.currFightLevelId;

            if (!UICopyData.CurrentLevelIsLastOfChapter(tempChapterId, tempLevelId))
            {
                UICopyData.GetNextRunningChapterAndLevel(out tempChapterId, out tempLevelId);
            }

            if ( UICopyData.GetUILevelData(tempLevelId).level_inst_open 
                && UICopyData.GetUIChapterData(tempChapterId).chapter_inst_open)
            {
                StaticData.currFightChapterId = tempChapterId;
                StaticData.currFightLevelId = tempLevelId;

                this.currentSelectionLevelId = tempLevelId;
                this.currentSelectionChapterId = tempChapterId;
            }
            else
            {
                this.currentSelectionLevelId = StaticData.currFightLevelId;
                this.currentSelectionChapterId = StaticData.currFightChapterId;
            }

            if (options.ContainsKey("chapterId"))
            {
                this.currentSelectionChapterId = options["chapterId"];
            }

            if (options.ContainsKey("levelId"))
            {
                this.currentSelectionLevelId = options["levelId"];
                var level = UICopyData.GetUILevelData(currentSelectionLevelId);
                this.currentSelectionChapterId = level.chapterId;
            }
            SwitchCopyPanel(CopyType.MainLine);

            RefreshChapters();
            RefreshLevels();
            RefreshDropDetail();
            RefreshPower();

            CheckLevelUp();


            CheckRebelInfo(); 
        }


        void CheckRebelInfo()
        {
            if (StaticData.lastBattleEndMsg != null && StaticData.curBattleData.battleType == BattleType.PVE)
            {
                var msg = (ProtoBuf.Message.SCCopyFightEnd)StaticData.lastBattleEndMsg;
                if (msg != null && msg.isCopyComplete > 0 && msg.wantedId != null)
                {
                    var rebel = msg.wantedId;
                    BoxManager.CreateMeetBossBox(rebel);
                }
            }
        }

        public void Refresh()
        {
            if ( options.ContainsKey( "chapterId" ) )
            {
                this.currentSelectionChapterId =  options["chapterId"];
            }
            else
            {
                this.currentSelectionChapterId = StaticData.currFightChapterId;
            }

            if( options.ContainsKey( "levelId" ) )
            {
                this.currentSelectionLevelId = options["levelId"];
                var level = UICopyData.GetUILevelData(currentSelectionLevelId);
                this.currentSelectionChapterId = level.chapterId;
            }
            else
            {
                this.currentSelectionLevelId   = StaticData.currFightLevelId;
            }

            SwitchCopyPanel( CopyType.MainLine );

            RefreshChapters();
            RefreshLevels();
            RefreshDropDetail();
            RefreshPower();

            CheckLevelUp();

            CheckRebelInfo();
        }
        

        protected override void DoClose()
        {
            StopAllCoroutines();
            if(!string.IsNullOrEmpty(copyTextureName))
            {
                AssetLoadHelper.Instance.UnloadBundle(copyTextureName);
                copyTextureName = null;
            }
            StaticData.beforeBattleLevel = -1;
        }

        public override void OnForceClose()
        {
            StaticData.beforeBattleLevel = StaticData.playerData.level;
            
        }
        public override void OnCoverPageOpen()
        {
            //beforeBattleLevel = StaticData.playerData.level;
        }

        void CheckLevelUp()
        {
            Story.StoryManager.Instance.OnCopyPageOpen(_CheckLevelUp);

            
        }
        void _CheckLevelUp()
        {
            if (StaticData.beforeBattleLevel > 0 && StaticData.beforeBattleLevel != StaticData.playerData.level)
            {
                BoxManager.CreateLevelUp(StaticData.beforeBattleLevel, StaticData.playerData.level);
                StaticData.beforeBattleLevel = -1;


                if (GuideManager.Instance==null||string.IsNullOrEmpty(GuideManager.Instance.GetGuideOfLevel(StaticData.playerData.level)))
                {
                    _CheckLuxuryEquipmentActivity();
                }
            }
            else
            {
                _CheckLuxuryEquipmentActivity();
            }
            
        }
        void _CheckLuxuryEquipmentActivity()
        {
            foreach(var data in Dict.DictDataManager.Instance.tableLuxuryEquipDao.CacheList)
            {
                var levelData = UICopyData.GetUILevelData(data.chapter.ToString(), data.stage);
                if(levelData.level_inst_star>0)
                {
                    if(!StaticData.listOpenedLuxuryEquipActivity.Contains(data.id))
                    {
                        var msg = new ProtoBuf.Message.CSOpenLuxuryEquipment();
                        msg.chapter = data.chapter;
                        msg.mission = data.stage;
                        NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSOpenLuxuryEquipment, msg,SCOpenLuxuryEquipmentCallBack);
                        break;
                    }
                    
                }
                
            }
        }
        void SCOpenLuxuryEquipmentCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                var _msg = packet.kBody as ProtoBuf.Message.SCOpenLuxuryEquipment;
                if (_msg.openOrNot == 1)
                {
                    StaticData.isOpeningLuxuryEquipActivity = true;
                    var msg = new ProtoBuf.Message.CSLuxuryEquipmentInfo();
                    NetAPI.SendHttp(ProtoBuf.Message.OpDefine.CSLuxuryEquipmentInfo, msg, SCLuxuryEquipmentInfoCallBack);
                }
            }
        }
        public void SCLuxuryEquipmentInfoCallBack(NetWork.Packets.Packet packet, bool bSuccess)
        {
            if (bSuccess)
            {
                var recv = packet.kBody as ProtoBuf.Message.SCLuxuryEquipmentInfo;
                string option = string.Format("id={0}&endTime={1}&rewardState={2}", recv.id, recv.endTime, recv.rewardState);
                if (recv != null)
                {
                    //PageManager.Instance.OpenPage("LuxuryEquipmentPage", option);
                    PageManager.Instance.OpenPage("LuxuryPage", option);
                }
            }
        }

        /// <summary>
        /// 章节
        /// </summary>
        void RefreshChapters()
        {
            StopCoroutine( "_CreateChapter" );
            StartCoroutine(_CreateChapter());
        }

        IEnumerator _CreateChapter()
        {
            foreach( var obj in chapters )
            {
                DestroyImmediate( obj );
            }
            chapterItemGrid.Reposition();
            chapters.Clear();

            yield return null;
            var chapterDatas = StaticData.copyData.copy_chapters;
            var totalChapters = chapterDatas.Count;
            int i=0;
            foreach (var cd in chapterDatas)
            {
                GameObject obj = GameObject.Instantiate( chapterItem ) as GameObject;
                obj.transform.SetParent( chapterItemGrid.transform );
                obj.transform.localScale = Vector3.one;
                obj.SetActive( true );
                obj.name = cd.chapter_id;
                var item = obj.GetComponent<UICopyChapterItem>();
                item.Init(cd,this);

                chapters.Add( obj );

                if( ++i%4==0 )
                {
                    chapterItemGrid.Reposition();
                    yield return null;
                }
            }


            var needSub = int.Parse(currentSelectionChapterId) - 1;
            if(int.Parse(currentSelectionChapterId) > (totalChapters - 4) )
            {
                needSub = totalChapters - 4;
            }
            var fixedOffset = 10f;
            var width = chapterItemGrid.cellWidth * (needSub) * -1f + fixedOffset;
            chapterScrollView.UpdatePosition();
            chapterScrollView.MoveRelative( new Vector3( width, 0, 0 ) );
            chapterItemGrid.Reposition();
        }

        public void ResetOptionStr()
        {
            if (UICopyData.GetUILevelData(currentSelectionLevelId).level_inst_star > 0)
            {
                options["chaperId"] = currentSelectionChapterId;
                options["levelId"] = currentSelectionLevelId;
            }
        }

        public void OnRefreshChapter(string selectonId)
        {
            if( this.currentSelectionChapterId != selectonId )
            {
                this.currentSelectionChapterId = selectonId;

                foreach( var chapter in chapters )
                {
                    var selection = chapter.GetComponent<UICopyChapterItem>().chapter_id == selectonId;
                    chapter.GetComponent<UICopyChapterItem>().chapterSelection.SetActive( selection );
                }


                this.currentSelectionLevelId = UICopyData.GetUILevelData( currentSelectionChapterId,1).level_id;
                RefreshLevels();
            }
        }

        /// <summary>
        /// 创建关卡
        /// </summary>
        void RefreshLevels()
        {
            StopCoroutine( "_CreateLevel" );
            StartCoroutine(_CreateLevel());
        }

        IEnumerator _CreateLevel()
        {
            foreach (var obj in levels)
            {
                DestroyImmediate( obj );
            }
            levels.Clear();
            levelItemGrid.Reposition();
            yield return null;
            
            var levelsData = UICopyData.GetUIChapterData( currentSelectionChapterId ).chapter_levels;
            int i=0;
            int seq=0;

            foreach (var levelData in levelsData)
            {
                GameObject obj = GameObject.Instantiate( levelItem ) as GameObject;
                obj.SetActive( true );
                obj.transform.SetParent( levelItemGrid.transform );
                obj.transform.localScale = Vector3.one;
                var level = obj.GetComponent<UICopyLevelItem>();
                level.Init( levelData, this );
                levels.Add( obj );
                if( levelData.level_id == this.currentSelectionLevelId )
                {
                    seq = levelData.level_seq;
                }
                if( ++i%5==0 )
                {
                    levelItemGrid.Reposition();
                    yield return null;
                }
            }

            
            levelItemGrid.Reposition();
            levelScrollVIew.transform.localPosition = levelScrollViewStart;
            levelScrollVIew.GetComponent<UIPanel>().clipOffset=levelScrollViewClipOffset;
            levelScrollVIew.ResetPosition();
         

            if (seq>=5)//列表内部显示5个多一点
            {
                var moveValue = (seq - 1) * levelItemGrid.cellHeight-320;//320是固定偏移量
                levelScrollVIew.MoveRelative(new Vector3(0, moveValue, 0));
                levelItemGrid.Reposition();
            }

            SetCurrentLevel( currentSelectionLevelId );
        }

        public void OnRefreshLevel( string selectionId)
        {
            if( this.currentSelectionLevelId!=selectionId  )
            {
                this.currentSelectionLevelId = selectionId;

                foreach( var level in levels )
                {
                    var levelItem = level.GetComponent<UICopyLevelItem>();
                    var selection = levelItem.id == selectionId;
                    levelItem.unSelection.SetActive( !selection );
                    levelItem.selection.SetActive( selection );
                    if( selection )
                    {
                        this.currLevel.text = levelItem.levelNumber.text;
                        this.currLevelName.text = levelItem.levelName.text;
                        SetMainCopyTexture( levelItem.bigIcon );
                    }
                }
                RefreshDropDetail();
            }
        }

        /// <summary>
        /// 设置当前的Level信息
        /// </summary>
        /// <param name="levelId"></param>
        void SetCurrentLevel( string levelId )
        {
            foreach( var level in levels )
            {
                var levelItem = level.GetComponent<UICopyLevelItem>();
                var selection = level.GetComponent<UICopyLevelItem>().selection.activeSelf;
                if(selection)
                {
                    this.currLevel.text = levelItem.levelNumber.text;
                    this.currLevelName.text = levelItem.levelName.text;
                    SetMainCopyTexture( levelItem.bigIcon );
                    break;
                }
            }
            
            RefreshStar();
            RefreshDropDetail();
        }

        /// <summary>
        /// 主面板的掉落显示
        /// </summary>
        public void RefreshDropDetail()
        {
            StopCoroutine( "_CreateRefreshDropDetail" );
            StartCoroutine(_CreateRefreshDropDetail());
            //_CreateRefreshDropDetail();
        }

        IEnumerator  _CreateRefreshDropDetail()
        {
            int coin = 0;
            int exp = 0;
            var level = UICopyData.GetUILevelData(currentSelectionLevelId);
            int power= level.level_power_cost;

            coin = Dict.Blo.DictCopyExpBlo.GetCoinByHeroLevel(StaticData.playerData.level);
            exp = Dict.Blo.DictCopyExpBlo.GetExpByHeroLevel(StaticData.playerData.level);

            this.awordMoney.text = coin.ToString();
            this.awordExp.text = exp.ToString();
            this.curCostPowerTxt.text = string.Format( TableTextBlo.GetText( "copy_cost_power" ), power );

            var str = TableTextBlo.GetText("copy_level_chanllage_count");
            var last = level.level_max_challenge - level.level_curr_challenge;
            this.currChallengeCount.text = string.Format(str, last, level.level_max_challenge); ;
            //yield return null;

            var dropData = UICopyData.GetUILevelData(currentSelectionLevelId).level_drop_show;

            UIDropData dropInfo = new UIDropData( dropData );


            if( this.drops.Count > 0 )
            {
                foreach (var obj in this.drops)
                {
                    Destroy( obj );
                }
            }

            foreach( var kv in dropInfo.drop_dict )
            {
                GameObject obj = GameObject.Instantiate( dropItem ) as GameObject;
                obj.SetActive( true );
                obj.transform.SetParent( dropItemGrid.transform );
                obj.transform.localScale = Vector3.one*0.9f;
                
                obj.GetComponent<CommonIcon>().SetData(kv.Key,true,-1);
                //yield return null;
                this.drops.Add( obj );
                yield return null;
                dropItemGrid.Reposition();
            }

            dropItemGrid.Reposition();
            yield return null;
            RefreshStar();
        }

        public void SetMainCopyTexture(string texPath)
        {
            string path = "copy/"+texPath;
            //var tex = Resources.Load( path ) as Texture;
            //this.currLevelTex.mainTexture = tex;
            if(!string.IsNullOrEmpty(copyTextureName) && copyTextureName != path)
            {
                AssetLoadHelper.Instance.UnloadBundle(copyTextureName);
            }
            copyTextureName = path;
            AssetLoadHelper.Instance.SetTextureAsync(currLevelTex, path, false);
        }

        /// <summary>
        /// 刷新体力面板
        /// </summary>
        public void RefreshPower()
        {
            StopCoroutine( "_SetPower" );
            StartCoroutine(_SetPower());
        }

        /// <summary>
        /// 刷新体力数
        /// </summary>
        /// <returns></returns>
        IEnumerator _SetPower()
        {
            fightBtn.SetActive(true);
            sweepBtn.SetActive(true);

            for (;;)
            {
                var curPower = StaticData.playerData.Stamina;
                var maxPower = StaticData.playerData.maxStamina;

                this.curPowerTxt.text = curPower+ "/"+maxPower;
                
                int maxCount = curPower / UICopyData.GetUILevelData(currentSelectionLevelId).level_power_cost;
          
                currentSweepCount = Mathf.Clamp(maxCount, 0, 10);

                int currChanllgeCount = UICopyData.GetUILevelData(currentSelectionLevelId).level_curr_challenge;
                int totalCount = UICopyData.GetUILevelData(currentSelectionLevelId).level_max_challenge;
                int lastChallengeCount = totalCount - currChanllgeCount;

                lastChallengeCount = Mathf.Clamp(lastChallengeCount, 0, 10);

                if (lastChallengeCount < currentSweepCount )
                {
                    currentSweepCount = lastChallengeCount;
                }

                sweepBtnCountTxt.text = string.Format(TableTextBlo.GetText("copy_sweep"), currentSweepCount);

                yield return new WaitForSeconds(0.8f);
            }
        }

        /// <summary>
        /// 刷新顶部星星数
        /// </summary>
        public void RefreshStar()
        {
            string instStar = UICopyData.GetChapterStar( currentSelectionChapterId )+"";
            string dictStar = UICopyData.GetChapterAllStar( currentSelectionChapterId )+"";
            this.curStarTxt.text = instStar+"/"+dictStar;

            foreach(var chapter in chapters)
            {
                var script = chapter.GetComponent<UICopyChapterItem>();
                script.RefreshStar();
            }

            RefreshTip();
        }

        /// <summary>
        /// 奖励红点提示
        /// </summary>
        public void RefreshTip()
        {
            var chapter = UICopyData.GetUIChapterData( currentSelectionChapterId );
            var star = UICopyData.GetChapterStar( chapter );

            bool needTip=false;
            if( !chapter.chapter_inst_get_box_0 && chapter.chapter_box_condition[0] <= star ) //宝箱0
            {
                needTip=true;
            }

            if( !chapter.chapter_inst_get_box_1 && chapter.chapter_box_condition[1] <= star ) //宝箱1
            {
                needTip=true;
            } 
            
            if( !chapter.chapter_inst_get_box_2 && chapter.chapter_box_condition[2] <= star ) //宝箱2
            {
                needTip=true;
            }

            currAwardTips.SetActive( needTip );


        }

        public void SwitchCopyPanel(CopyType ct)
        {
            mainLineCopy.SetActive( false );
            groupCopy.SetActive( false );

            if( ct == CopyType.MainLine )
            {
                mainLineCopy.SetActive( true );
            }
            else if( ct == CopyType.Group )
            {
                groupCopy.SetActive( true );
            }
        }

        void Start()
        {
            DataMessageTool.AddHandler(DataMessage.RED_POINT, ShowOrHideRedPoint);//红点消息处理委托
            ShowOrHideRedPoint(new object());
        }

        void OnDestroy()
        {
            DataMessageTool.RemoveHandler(DataMessage.RED_POINT, ShowOrHideRedPoint);
        }

        void ShowOrHideRedPoint(object redPoint)
        {
            
        }
    }
}